package main

import (
	"encoding/json"
	"log"
	"strconv"

	"gitee.com/shiwjlinux/MessageQueue/nats01/model"
	"github.com/nats-io/nats.go"
)

func main() {
	nc, _ := nats.Connect(model.NatsURL)
	js, err := nc.JetStream()
	checkErr(err)

	err = createStream(js)
	checkErr(err)

	err = createOrder(js)
	checkErr(err)
}

func createOrder(js nats.JetStreamContext) error {
	var order model.Order
	for i := 1; i < model.OrderNumber; i++ {
		order = model.Order{
			OrderID:     i,
			CustormerID: "Cust-" + strconv.Itoa(i),
			Status:      "created",
		}
		orderJSON, _ := json.Marshal(order)
		_, err := js.Publish(model.SubjectName, orderJSON)
		if err != nil {
			return err
		}
		log.Printf("Order with OrderID:%d has been published\n", order.OrderID)

	}
	return nil
}

func createStream(js nats.JetStreamContext) error {
	stream, err := js.StreamInfo(model.StreamName)
	if err != nil {
		log.Println(err)
	}
	if stream == nil {
		log.Printf("creating stream %q and subjects %q", model.StreamName, model.StreamSubjects)
		_, err := js.AddStream(&nats.StreamConfig{
			Name:     model.StreamName,
			Subjects: []string{model.StreamSubjects},
		})
		if err != nil {
			return err
		}
	}

	return nil
}

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}
